package com.hq.fxh.imageLoader;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;


import com.hq.fxh.No2_BBS.Activity.PlateEditorActivity;
import com.hq.fxh.R;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.Tool;
import com.hq.fxh.imageLoader.bean.ImageFolder;
import com.hq.fxh.imageLoader.bean.ImageItem;

import java.io.Serializable;
import java.util.List;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;

public class SelectPictureActivity extends ImageBaseActivity implements ImageDataSource.OnImagesLoadedListener, ImageGridAdapter.OnImageItemClickListener, ImagePicker.OnImageSelectedListener, View.OnClickListener {


    public static final int REQUEST_PERMISSION_STORAGE = 0x01;
    public static final int REQUEST_PERMISSION_CAMERA = 0x02;

    private ImagePicker imagePicker;

    private boolean isOrigin = false;  //是否选中原图
    private GridView mGridView;  //图片展示控件
    private TextView tvOk;       //确定按钮
    private TextView mBtnDir;      //文件夹切换按钮
    private List<ImageFolder> mImageFolders;   //所有的图片文件夹
    private ImageGridAdapter mImageGridAdapter;  //图片九宫格展示的适配器
    private ImageFolder OneImageFolder;
    private boolean isTransFolder = false;
    private TextView tv_select_count;
    private TextView tv_title;
    private boolean isAddMorePic;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_video;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isAddMorePic = getIntent().getBooleanExtra("IsAddMorePic",false);
        imagePicker = ImagePicker.getInstance();
        if (!isAddMorePic) {//从图片完成界面添加图片跳转过来时，imagePicker不清空
            imagePicker.clearSelectedImages();
        }
        //图片加载完成是回调该接口
        imagePicker.addOnImageSelectedListener(this);

        findViewById(R.id.btn_back).setOnClickListener(this);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        tvOk.setOnClickListener(this);
        tv_select_count = (TextView) findViewById(R.id.tv_select_count);
        mBtnDir = (TextView) findViewById(R.id.btn_dir);
        mBtnDir.setOnClickListener(this);
        mGridView = (GridView) findViewById(R.id.gridview);
        tv_title = (TextView) findViewById(R.id.tv_title);
        if (imagePicker.isMultiMode()) {
            tvOk.setVisibility(View.VISIBLE);
        }

        mImageGridAdapter = new ImageGridAdapter(this, null);
        Intent intent = this.getIntent();
        OneImageFolder = (ImageFolder) intent.getSerializableExtra("OneimageFolder");
        isTransFolder = intent.getBooleanExtra("isTransFolder", false);
        if (null != OneImageFolder && isTransFolder) {
            mImageGridAdapter.refreshData(OneImageFolder.images);
            tv_title.setText(OneImageFolder.name);
            mBtnDir.setVisibility(View.GONE);
            mImageGridAdapter.setShowCamera(false);
        }else {
            mImageGridAdapter.setShowCamera(true);
        }
        onImageSelected(0, null, false);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                new ImageDataSource(this, null, this);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_STORAGE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mImageGridAdapter.notifyDataSetChanged();
        JAnalyticsInterface.onPageStart(this,"选择图片相册");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new ImageDataSource(this, null, this);
            } else {
                showToast("权限被禁止，无法选择本地图片");
            }
        } else if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imagePicker.takePicture(this, ImagePicker.REQUEST_IMAGE_TAKE);
            } else {
                showToast("权限被禁止，无法打开相机");
            }
        }
    }

    @Override
    protected void onDestroy() {
        imagePicker.removeOnImageSelectedListener(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_ok) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
            Tool.openActivity(SelectPictureActivity.this, PlateEditorActivity.class, bundle);
        } else if (id == R.id.btn_dir) {
            if (mImageFolders == null) {
                LogUtils.startToash(SelectPictureActivity.this, "您的手机没有图片");
                return;
            }
            //点击文件夹按钮
            Bundle bundle = new Bundle();
            bundle.putSerializable("ImageFolders", (Serializable) mImageFolders);
            Tool.openActivity(SelectPictureActivity.this, FolderPictureActivity.class, bundle);
        } else if (id == R.id.btn_back) {
            //点击返回按钮
            finish();
        }
    }

    @Override
    public void onImagesLoaded(List<ImageFolder> imageFolders) {
        this.mImageFolders = imageFolders;
        imagePicker.setImageFolders(imageFolders);
        if (imageFolders.size() == 0) mImageGridAdapter.refreshData(null);
        else if (!isTransFolder) {
            mImageGridAdapter.refreshData(imageFolders.get(0).images);
        }
        mImageGridAdapter.setOnImageItemClickListener(this);
        mGridView.setAdapter(mImageGridAdapter);
    }

    @Override
    public void onImageItemClick(View view, ImageItem imageItem, int position) {
        //根据是否有相机按钮确定位置
        position = mImageGridAdapter.isShowCamera() ? position - 1 : position;
        if (imagePicker.isMultiMode()) {
            Intent intent = new Intent(SelectPictureActivity.this, ImagePreviewActivity.class);
            intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
            intent.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageGridAdapter.getImages());
            intent.putExtra(ImagePreviewActivity.ISORIGIN, isOrigin);
            startActivityForResult(intent, ImagePicker.REQUEST_IMAGE_PREVIEW);  //如果是多选，点击图片进入预览界面
        }
    }

    @Override
    public void onImageSelected(int position, ImageItem item, boolean isAdd) {
        if (imagePicker.getSelectImageCount() >= 0) {
            tv_select_count.setText(getString(R.string.select_complete, "   " + imagePicker.getSelectImageCount(), imagePicker.getSelectLimit()));
        } else {
            tvOk.setText(getString(R.string.complete));
        }
//        mImageGridAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == ImagePicker.RESULT_IMAGE_BACK) {
//                isOrigin = data.getBooleanExtra(ImagePreviewActivity.ISORIGIN, false);
                isOrigin = data.getBooleanExtra("isOrigin", false);
            } else {
                //从拍照界面返回
                //点击 X , 没有选择照片
                if (data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) == null) {
                    //什么都不做
                } else {
                    //说明是从裁剪页面过来的数据，直接返回就可以
                    setResult(ImagePicker.RESULT_IMAGE_ITEMS, data);
                    finish();
                }
            }
        } else {
            //如果是裁剪，因为裁剪指定了存储的Uri，所以返回的data一定为null
            if (resultCode == RESULT_OK && requestCode == ImagePicker.REQUEST_IMAGE_TAKE) {
                //发送广播通知图片增加了
                ImagePicker.galleryAddPic(this, imagePicker.getTakeImageFile());
                ImageItem imageItem = new ImageItem();
                imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
                imagePicker.clearSelectedImages();
                imagePicker.addSelectedImageItem(0, imageItem, true);
                if (imagePicker.isCrop()) {
//                    Intent intent = new Intent(SelectPictureActivity.this, ImageCropActivity.class);
//                    startActivityForResult(intent, ImagePicker.REQUEST_IMAGE_CROP);  //单选需要裁剪，进入裁剪界面
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
                    setResult(ImagePicker.RESULT_IMAGE_ITEMS, intent);   //单选不需要裁剪，返回数据
                    finish();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        JAnalyticsInterface.onPageEnd(this,"选择图片相册");
    }

}
